//创建用户相关的小仓库
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo } from '../../api/user'
import type { loginForm, loginResData } from '../../api/user/type'
import type { useState } from './type'
import { anyRoutes, asyncRoutes, constantRoutes } from '../../router/routes'
import router from '../../router'
import { cloneDeep } from 'lodash'

//用于过滤异步路由信息
function filterAsyncRoutes(asyncRoutes: any, routes: any) {
    return asyncRoutes.filter((item: any) => {
        if(routes.includes(item.name)) {
            if(item.children && item.children.length > 0) {
               item.children = filterAsyncRoutes(item.children, routes)
            }
            return true
        }
    })
}
let useUserStore = defineStore('User', {
    //小仓库存储数据地方
    state: (): useState => {
        return {
            token: localStorage.getItem("TOKEN") as string,//用户唯一标识
            username: '',
            avatar: '',
            menuRoutes: constantRoutes
        }
    },
    //异步|逻辑的地方
    actions: {
        async userLogin(data: loginForm) {
            let result: loginResData = await reqLogin(data) // 先不发请求
            // let result = {
            //     code: 200,
            //     data: 'sjdkdg'
            // }
            if (result.code == 200) {
                this.token = result.data as string
                //由于pina|vuex存储数据都不是持久化的，只是一个js对象，因此需要如下持久化代码
                //pina也有相应的持久化插件
                localStorage.setItem("TOKEN", this.token)
                //保证当前async函数返回一个成功的promise对象
                return 'ok'
            } else {
                return Promise.reject(new Error('登录失败'))
            }
        },
        async userInfo() {
            let res = await reqUserInfo()
            this.username = res.data.name
            this.avatar = res.data.avatar
            //获取用户信息成功的时候，在这里计算当前用户所需要的异步路由信息
            let userAsyncRoutes = filterAsyncRoutes(cloneDeep(asyncRoutes), res.data.routes)
            //这里只是把菜单的路由信息准备好了，路由器里面还需要搞一下，不然只是有菜单按钮但是不能点
            this.menuRoutes = [...constantRoutes, ...userAsyncRoutes, ...anyRoutes]
            userAsyncRoutes.forEach((item: any) => {
                router.addRoute(item)
            });
            anyRoutes.forEach((item: any) => {
                router.addRoute(item)
            })
            return 'ok'
        },
        loginOut() {
            //将用户信息清空，包括token和头像相关的。
            this.token = ''
            localStorage.removeItem('TOKEN')
            this.username = ''
            this.avatar = ''
        }
    },
    getters: {

    }
})
//对外暴露获取小仓库方法
export default useUserStore